package com.mozai.shopping.service.impl;

import com.mozai.shopping.config.Constant;
import com.mozai.shopping.dao.UserDao;
import com.mozai.shopping.model.User;
import com.mozai.shopping.model.base.BaseResponse;
import com.mozai.shopping.model.base.ErrorMessage;
import com.mozai.shopping.model.http.UserReq;
import com.mozai.shopping.service.UserService;
import com.mozai.shopping.utils.JWTUtil;
import com.mozai.shopping.utils.MD5Util;
import com.mozai.shopping.utils.bean.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Target;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Override
    public BaseResponse login(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, UserReq userReq) {
        HttpSession session = httpServletRequest.getSession();
        Token tokenVo =new Token();
        //加密密码
        String encryptPassword =MD5Util.encrypt(userReq.getPassword());

        //查询用户
        User user2=new User();
        user2=userDao.selectUser(userReq.getUserName());
        if (user2.getUserName()==null){
            return BaseResponse.error(ErrorMessage.LOGIN_NO_USER);
        }
        //判断密码
        Map<String,Object> claims =new HashMap<>();
        claims.put(Constant.SESSION_KEY,user2);
        session.setAttribute(Constant.SESSION_KEY,user2);
        String token =JWTUtil.generateJwt(claims);

        tokenVo.setToken(token);
        tokenVo.setUserId(user2.getId());
        tokenVo.setLongTime(System.currentTimeMillis());
        return BaseResponse.ok(tokenVo);
    }
}
